<?php

namespace app\service;


use app\model\TaskModel;
use app\tool\SingletonTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class ProductionInfoReportService
{
    use SingletonTrait;


    /**
     * 生产信息简报
     * @param int $projectId
     * @param int $startTime
     * @param int $endTime
     * @param $departmentId
     * @param $todoStepCategoryId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function productionInfoReport(int $projectId, int $startTime, int $endTime, $departmentId, $todoStepCategoryId): array
    {
        $field = [
            'task.id as task_id',
            'task.name as task_name',
            'task.plan_start_time',
            'task.plan_end_time',
            'task.end_time',
            'trt.link_id as episode_id',
            'episode.name as episode_name',
            "get_json_string(task.`json`,'$.task_status') as task_status"
        ];
        $closedStatusId = StatusService::getInstance()->byCode('closed')['id'];
        $finalStatusId = StatusService::getInstance()->byCode('final')['id'];

        $productionInfoReportModel = (new \app\model\TaskModel)->field($field)->cache(5);
        $productionInfoReportModel->join("task_relation_tag trt", "task.id = trt.task_id and link_module_code = 'episode'");
        $productionInfoReportModel->join("(select id,name from entity) episode", 'episode.id = trt.link_id');

        if (!empty($departmentId) || !empty($todoStepCategoryId)) {
            $tenantId = request()->getTenantId();
            $saasUserId = [request()->getSaasUserId()];
            $queryArrayFilter['department_id'] = $departmentId;
            $queryArrayFilter['step_category_id'] = $todoStepCategoryId;
            $queryArrayConstruct = query_array_construct([
                'department_id' => 'intval',
                'step_category_id' => 'split_array|array_map,intval',
            ], $queryArrayFilter);
            TaskStatisticsService::getInstance()->taskMyResponsibleFilter($productionInfoReportModel, $queryArrayConstruct, $saasUserId, $tenantId);
        }
        $productionInfoReportList = $productionInfoReportModel
            ->whereIn('task.step_type', [TaskModel::STEP_TYPE_STANDARD_REVIEW, TaskModel::STEP_TYPE_STANDARD_MEETING])
            ->where('task.project_id', $projectId)
            ->whereRaw("(task.plan_end_time >= {$startTime} and task.plan_start_time <= {$endTime})")
            ->whereFieldRaw("get_json_string(task.`json`,'$.task_status')", '<>', $closedStatusId)
            ->select()
            ->order('task.id asc')
            ->toArray();
        if (empty($productionInfoReportList)) {
            return [];
        }
        $taskIds = array_column($productionInfoReportList, 'task_id');

        // 查询加班完成【今日完成,但是任务在推送日报的时候,还未完成】
        $delayOrderTaskModel = (new \app\model\DelayOrderTaskModel)->field('task.id as task_id');
        $delayOrderTaskModel->join('task', 'task.id = delay_order_task.task_id');
        $delayOrderTaskList = $delayOrderTaskModel
            ->where('delay_order_task.type', 'today_done')
            ->whereIn('task.id', $taskIds)
            ->whereBetween('delay_order_task.original_plan_time', [$startTime, $endTime])
            ->whereFieldRaw("get_json_string(task.`json`,'$.task_status')", '<>', $closedStatusId)
            ->whereFieldRaw("get_json_string(task.`json`,'$.task_status')", '<>', $finalStatusId)
            ->column('task_id');
        if (empty($delayOrderTaskList)) {
            $delayOrderTaskList = [];
        }
        return array_map(function ($tmp) use ($delayOrderTaskList) {
            $tmp['overtime'] = 'no';
            if (in_array($tmp['task_id'], $delayOrderTaskList)) {
                $tmp['overtime'] = 'yes';
            }
            $tmp['task_status'] = StatusService::getInstance()->byId($tmp['task_status']);
            return $tmp;
        }, $productionInfoReportList);
    }

}
